/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/util/config/MybatisConfiguration.java.hbs
 */
package cn.ibizlab.util.tenant;

import cn.ibizlab.util.db.dialect.MySqlDialect;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


@Configuration
@ConditionalOnExpression("'${ibiz.tenant.enabled:false}'.equals('true')")
public class TenantConfiguration {

    /**
     * 多租户插件/分页拦截器
     * @param dataSource
     * @param tenantHandler
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(DataSource dataSource , TenantHandler tenantHandler) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantHandler));
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        initDialect(dataSource,paginationInnerInterceptor);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

    public void initDialect(DataSource dataSource, PaginationInnerInterceptor paginationInnerInterceptor) {
        try (Connection connection  = dataSource.getConnection() ) {
            DbType dbType = JdbcUtils.getDbType(connection.getMetaData().getURL());
            if (dbType == DbType.MYSQL) {
                Properties properties = new Properties();
                properties.put("dialect", MySqlDialect.class.getCanonicalName());
                paginationInnerInterceptor.setProperties(properties);
            }
        } catch (SQLException e) {

        }
    }

}